package com.haoxi.gateway.test.gatewayserver;


import java.net.Socket;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Administrator Window - Preferences - Java - Code Style - Code
 *         Templates
 */
public class PooledConnHandler implements Runnable {

    protected static final Log log = LogFactory
            .getLog(PooledConnHandler.class);
    
    protected static List pool = new LinkedList();

    public PooledConnHandler() {
    }

    //往处理池，添加一个需要处理的请求
    public static void processRequest(Socket requestToHandle) {
        synchronized (pool) {
            pool.add(pool.size(), requestToHandle);
            pool.notifyAll();
        }
    }
    
    /**
     * 具体的处理
     * 
     * @param socketConn
     *            请求
     */
    public void process(Socket socketConn) {}

    /**
     * 运行
     */
    public void run() {
        Object obj = null;
        while (true) {
            synchronized (pool) {
                if (pool.isEmpty()) {
                    try {

                        //server所有的线程都等待
                        pool.wait();

                    } catch (InterruptedException e) {
                        continue;
                    }
                }
                //在池不空的时候进行处理
                else {
                    obj = pool.remove(0);
                    if (obj instanceof Socket) {
                        try {
                            process((Socket) obj);
                        } catch(Exception e) {
                            log.error("process error:", e);
                        }
                    }
                }
            }
        }
    }
}